package com.hanma.util;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 文件上传工具类
 * 
 * @author Lenovo
 *
 */
public class FileUtil {

	public static String upload(HttpServletRequest request, String path) {
		// 获取磁盘文件工厂类的对象
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 获取解析器的对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> list = null;
		try {
			list = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		String url = "";
		for (FileItem item : list) {
			if (!item.isFormField()) {
				String fileName = item.getName();
				if (fileName != null && !fileName.isEmpty()) {
					// Only process file-related operations if a file is uploaded
					String newName = getUUIDFileName(fileName);
					InputStream is;
					try {
						is = item.getInputStream();
						File file = new File(path);
						if(!file.exists()){
							file.mkdir();
						}
						url = path + "\\" + newName;
						item.write(new File(url));
						is.close();
						return newName;
					}catch (Exception e){
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}


	public static String getUUIDFileName(String fileName) {
		int index = fileName.lastIndexOf(".");
		String ext = fileName.substring(index);
		System.out.println(UUID.randomUUID());
        return UUID.randomUUID().toString().replace("-", "")+ext;
	}
}
